﻿using Report_Unity.Basic;
using Report_Unity.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Filters;

namespace ReportWebApi.Filters
{
    public class GlobalExceptionAttribute : ExceptionFilterAttribute
    {
        private LogHelper logHelper = new LogHelper(typeof(GlobalExceptionAttribute));

        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            logHelper.Error(actionExecutedContext.Exception.Message, actionExecutedContext.Exception);

            // 把当前请求的返回指定一下
            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(
                HttpStatusCode.InternalServerError, CodeStatus.error_500.GetStatus(actionExecutedContext.Exception.Message));


            string Origin = "Origin";

            if (actionExecutedContext.Request.Headers.Contains(Origin))
            {
                string originUrl = actionExecutedContext.Request.Headers.GetValues(Origin).FirstOrDefault();
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", originUrl);
            }

            // actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");

            base.OnException(actionExecutedContext);
        }
    }
}